import json
import time

from pages.basePage import BasePage
from tools.request import Base
from tools.logs import Logs

logger = Logs(__name__).get_logger()


class GpBk(BasePage):

    def __init__(self):
        super().__init__()
        self.request = Base()
        self.gp_bk_xpath = '//*[@class="gntc_content"]/ul/li'
        self.bk_zdf_xpath = '//*[@class="stock"]/li/div[2]/text()'
        self.bk_name_xpath = '//*[@class="stock"]/li/div[1]/text()'
        self.all_bk_url_xpath = '//*[@class="list_li"]/a/@href'
        self.all_bk_text_xpath = '//*[@class="list_li"]/a/text()'

    def re_bk_name(self, bk_url):
        """
        :param bk_url: /hangye/hy474.html
        :return:
        """
        bk_id = bk_url.split(".")[0].split("hy")[-1]
        return "BK0" + bk_id if len(bk_id) == 3 else "BK" + bk_id

    def get_all_bk(self, html) -> list:
        """
        行业板块url = 'https://stock.eastmoney.com/hangye.html'
        行业板块xpath = ''
        :return:
        """
        bk_list = []
        bk_url_list = self.request.parse(html, self.all_bk_url_xpath)
        bk_text_list = self.request.parse(html, self.all_bk_text_xpath)
        for i, j in zip(bk_url_list, bk_text_list):
            bk_list.append(dict(name=j, dm=self.re_bk_name(i)))
        return bk_list

    def is_bk_zt_one_page(self, html):
        """
        判断板块股票中有没有涨停的大哥，有一个大哥就加1
        :param html:
        :return:
        """
        bk_zdf = self.request.parse(html, self.bk_zdf_xpath)
        bk_name = self.request.parse(html, self.bk_name_xpath)
        is_zt = 0
        for i, j in zip(bk_zdf, bk_name):
            logger.info(f"板块下的股票：{j}，涨幅：{i}")
            i_l = i.split(" ")[-1].replace("%", "")
            if i_l == "--":
                continue
            if float(i_l) > 9.7:
                is_zt += 1

        return is_zt

    def is_bk_zt_pages(self, pages):
        """
        多个页面处理
        :param pages:
        :return:
        """
        if len(pages) == 0:
            return 0
        is_zt_count = 0
        for html in pages:
            is_zt_count += self.is_bk_zt_one_page(html)
        return is_zt_count

    def get_other_by_bk(self, url) -> list:
        """
        点击板块按钮，获取板块数据
        :return: 页面列表
        """
        page_list = []
        # gp_page = self.get_page_source(url)
        el = self.get_elements_xpath(self.gp_bk_xpath)
        logger.info("拿到所有的板块列表")
        if self.bk_is_red(el):
            for i in el:
                logger.info(f"遍历板块名：{i.text}")
                i.click()
                # 页面切换物理等待1秒
                time.sleep(1)
                gp_page = self.get_page_source(url)
                page_list.append(gp_page)
        return page_list

    def bk_is_red(self, bk_list):
        """
        3个板块一下，不判断，3-5 个板块必须红1个，5个以上板块必须红2两个
        :return:
        """
        count = 0
        for i in bk_list:
            if not isinstance(i, str):
                i = i.text
            zf = i.split(" ")[-1]
            if float(zf.replace("%", "")) > 0:
                count += 1
        if len(bk_list) <= 3:
            logger.info("板块不足3个，不统计涨幅数量")
            return True
        if 3 < len(bk_list) <= 5 and count >= 1:
            logger.info("板块大于3个，小于5个，涨幅数量必须大于1个")
            return True
        if len(bk_list) > 5 and count >= 2:
            logger.info("板块大于5个，涨幅数量必须大于2个")
            return True
        return False

    def today_lr(self, gp_data):
        """
        计算今日净流入，然后从大到小排序
        :param gp_data:
        :return:
        """
        pass

    def get_bk_zj(self, bk_id):
        """
        计算板块5日资金是否为正流入
        :return:
        """
        url = f'https://data.eastmoney.com/bkzj/{bk_id}.html'
        # 获取板块页面数据
        bk_page = self.get_page_source(url)
        # 获取页面上最近5天的资金量
        num = 5
        xpath = '//*[@id="table_ls"]/table/tbody/tr[{}]/td[2]/span/text()'
        sum_zj = 0
        for i in range(1, num + 1):
            zj = self.request.parse(bk_page, xpath.format(i))[0]
            zj = self.unit_change(zj)
            # print(f'第{i}天资金：{zj}')
            sum_zj += zj
        if sum_zj > 0:
            return True
        return False

    def get_gp_by_zs(self):
        """
        每天下午2点计算数据
        1、获取所有的行业板块列表
        行业板块url = 'https://stock.eastmoney.com/hangye.html'
        行业板块xpath = '//*[@class="list_li"]'
            1.1、根据指数的三要素筛选符合条件的板块
                1、5日内有至少一个净流入的或者连续5日都是净流出
                2、10日指数上涨趋势（当日收盘价需要高于10日最低价）
        2、根据指数去获取个股列表
            1、成交量3日最低，当日为震荡下跌，5日为上涨趋势，5日资金净流入，当日上涨，当日资金净流入

        :return:
        """
        pass


if __name__ == '__main__':
    gb = GpBk()
    html = gb.get_page_source('https://stock.eastmoney.com/hangye.html')
    ll = gb.get_all_bk(html)
    print(json.dumps(ll))
